// pages/index/index.js
let myRequest = require('../../config/myRequest.js');
let api = require('../../config/api.js');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    form: {
      orderIndex: '1',
      disposeIndex: 0,
    },
    listData: [],
    order: [{
        name: '1',
        value: '新订单',
        checked: 'true'
      },
      {
        name: '2',
        value: '退款单'
      },
      {
        name: '3',
        value: '售后订单'
      }
    ],
    orderStauts: [{
      name: '1',
      value: '同意',
      checked: 'true'
    }, {
      name: '2',
      value: '拒绝'
    }],
    orderStautsList: [{
      name: '1',
      value: '同意',
      checked: 'true'
    }, {
      name: '2',
      value: '拒绝'
    }],
    dispose: [{
        name: '0',
        value: '待处理',
        checked: 'true'
      },
      {
        name: '1',
        value: '已处理'
      },
    ],
    indexx: 0,
    objectArray: [{
        id: 10,
        name: '全部订单'
      },
      {
        id: 0,
        name: '配送订单'
      },
      {
        id: 1,
        name: '自提订单'
      }
    ],
    limit: 10,
    page: 1,
    isEnd: false,
    hintSow: false,
    hintType: 1,
    afterForm: {
      refund_money: '',
      id: '',
      // user_money:'',
      refund_integral: '',
      status: '1',
      refund_mark: '',
      user_moneys: '',
      refund_moneys: '',
      refund_integrals: '',
      orderId: '',
      orderStatus: '1',
      orderRemark: '',
      lmgList: [],
    },
    domain: api.domain,
    keyword: '', //搜索订单
    shipping_mode: '10', //订单方式
    isPickerRender: false,
    isPickerShow: false,
    start_date: "",
    end_date: "",
    pickerConfig: {
      endDate: true, // 是否需要结束时间，为true时显示开始时间和结束时间两个picker
      column: "", //可选的最小时间范围hour、minute、secend
      dateLimit: true, //是否现在时间可选范围，false时可选任意时间；当为数字n时，范围是当前时间的最近n天
      initStartTime: "2022-03-01", //picker初始时间，默认当前时间
      initEndTime: "2022-04-05", //picker初始结束时间，默认当前时间
      limitStartTime: "2022-01-01", //最小可选时间
      limitEndTime: "2055-01-01" //最大可选时间 
    },
    searchlabel: '按日期查询',
    checkAll: false,
    afterDec: [] // 售后订单详情
  },
  stopMove() {
    return;
  },
  bindChange: function (e) {
    const that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var values = that.data.objectArray[e.detail.value].id
    that.setData({
      shipping_mode: values,
      indexx: e.detail.value
    })
    that.getData()
  },
  pickerShow: function () {
    this.setData({
      isPickerShow: true,
      isPickerRender: true,
      chartHide: true
    });
  },
  pickerHide: function () {
    this.setData({
      isPickerShow: false,
      chartHide: false
    });
  },

  bindPickerChange: function (e) {
    console.log("picker发送选择改变，携带值为", e.detail.value);
    console.log(this.data.sensorList);
    this.getData(this.data.sensorList[e.detail.value].id);
    // let startDate = util.formatTime(new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * 7));
    // let endDate = util.formatTime(new Date());
    this.setData({
      index: e.detail.value,
      sensorId: this.data.sensorList[e.detail.value].id
      // startDate,
      // endDate
    });
  },
  setPickerTime: function (val) {
    const that = this;
    console.log(val);
    let data = val.detail;
    console.log(data);
    this.setData({
      start_date: data.startTime,
      end_date: data.endTime,
      searchlabel: data.startTime + '至' + data.endTime
    });
    that.getData()
  },

  getnowdate() {
    var date = new Date()
    var mymon = (date.getMonth() + 1)
    var mydate = date.getDate();
    if ((date.getMonth() + 1) < 10) {
      mymon = '0' + (date.getMonth() + 1); //补齐
    }
    if (date.getDate() < 10) {
      mydate = '0' + date.getDate(); //补齐
    }
    var myDate = date.getFullYear() + '-' + mymon + '-' +
      mydate
    var yrDate = this.GetPreMonthDay(myDate, 1);
    this.setData({
      start_date: yrDate,
      end_date: myDate,
      searchlabel: yrDate + '至' + myDate
    });
  },

  /**
   *获取几个月前的输入日期
   *{param:DateTime} date 输入日期(YYYY-MM-DD)
   *{param:number } monthNum 月数
   */
  GetPreMonthDay(date, monthNum) {
    var dateArr = date.split('-');
    var year = dateArr[0]; //获取当前日期的年份
    var month = dateArr[1]; //获取当前日期的月份
    var day = dateArr[2]; //获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); //获取当前日期中月的天数
    var year2 = year;
    var month2 = parseInt(month) - monthNum;
    if (month2 <= 0) {
      var absM = Math.abs(month2);
      year2 = parseInt(year2) - Math.ceil(absM / 12 == 0 ? 1 : parseInt(absM) / 12);
      month2 = 12 - (absM % 12);
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
      day2 = days2;
    }
    if (month2 < 10) {
      month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2 + '-' + day2;
    return t2;
  },

  // 选中一个商品
  switchGoodDetail(e) {
    const that = this;
    let index = e.currentTarget.dataset.index;
    let lists = that.data.listData;
    let boot = lists[index].checked
    if (boot) {
      that.setData({
        [`listData[${index}].checked`]: false
      })
    } else {
      that.setData({
        [`listData[${index}].checked`]: true
      })
    }
    let checkAll = lists.every(item => {
      return item.checked
    })
    that.setData({
      checkAll
    })

  },
  // 全选
  pitchAll() {
    const that = this;
    let checkAll = that.data.checkAll;
    let storeList = that.data.listData || [];
    let listStates = [];
    storeList.forEach((item, index) => {
      item.checked = !checkAll
    })
    that.setData({
      [`listData`]: storeList,
      checkAll: !checkAll
    })
  },
  //售后详情
  afterDetail(e) {
    const that = this;
    wx.navigateTo({
      url: `/pages/part/pages/AfterTheDetails/AfterTheDetails?id=${e.currentTarget.dataset.order_id}`
    })
  },
  inpRefund_money(e) {
    const that = this;
    that.setData({
      [`afterForm.refund_money`]: e.detail.value,
    })
  },
  // inpUser_money(e) {
  //   const that = this;
  //   that.setData({
  //     [`afterForm.user_money`]: e.detail.value,
  //   })
  // },
  inpRefund_integral(e) {
    const that = this;
    that.setData({
      [`afterForm.refund_integral`]: e.detail.value,
    })
  },
  inpRefund_mark(e) {
    const that = this;
    that.setData({
      [`afterForm.refund_mark`]: e.detail.value,
    })
  },
  //退款单意见
  refund_mark(e) {
    const that = this;
    that.setData({
      [`afterForm.orderRemark`]: e.detail.value,
    })
  },
  //状态切换
  orderStauts(e) {
    const that = this;
    that.setData({
      [`afterForm.status`]: e.detail.value,
    })
  },
  //退款单状态切换
  refundStauts(e) {
    const that = this;
    that.setData({
      [`afterForm.orderStatus`]: e.detail.value,
    })
  },
  hintCancel() {
    const that = this;
    that.setData({
      hintSow: false,
      [`afterForm.status`]: '1',
      [`afterForm.refund_money`]: '',
      // [`afterForm.user_money`]: "",
      [`afterForm.refund_integral`]: '',
      [`afterForm.refund_moneys`]: '',
      [`afterForm.user_moneys`]: "",
      [`afterForm.refund_integrals`]: '',
      [`afterForm.refund_mark`]: "",
      [`afterForm.orderId`]: "",
      [`afterForm.orderStatus`]: "1",
      [`afterForm.orderRemark`]: ""
    })
  },
  //退款单确定
  refundBtn() {
    const that = this;
    let json = {
      token: app.globalData.token,
      order_id: that.data.afterForm.orderId,
      status: that.data.afterForm.orderStatus,
      remark: that.data.afterForm.orderRemark
    }
    console.log(json)
    wx.showModal({
      content: '提交订单？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          myRequest.EasyHttp.post(api.reqUrls.confirmRefund, json).then((res) => {
            if (res.data.status == 1) {
              wx.showToast({
                title: '处理成功',
                icon: 'success',
                duration: 2000
              })
              that.hintCancel()
              that.getData()
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'error',
                duration: 2000
              })
              that.hintCancel()
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  hintBtn() {
    const that = this;

    if (parseFloat(that.data.afterForm.refund_money) > parseFloat(that.data.afterForm.refund_moneys)) {
      wx.showModal({
        showCancel: false,
        content: '不能大于支付金额',
        success(res) {
          if (res.confirm) {

          }
        }
      })
      return false
    }
    if (that.data.afterForm.status == 1) {
      if (that.data.afterForm.refund_money.length == 0 || that.data.afterForm.refund_money == 0) {
        wx.showModal({
          showCancel: false,
          content: '退还支付金额不能为空，不能为0',
          success(res) {
            if (res.confirm) {

            }
          }
        })
        return false
      }
    }
    if (parseFloat(that.data.afterForm.refund_integral) > parseFloat(that.data.afterForm.refund_integrals)) {
      wx.showModal({
        showCancel: false,
        content: '不能大于使用积分',
        success(res) {
          if (res.confirm) {

          }
        }
      })
      return false
    }
    let specialName = that.hasSpecial(that.data.afterForm.refund_mark);
      // 判断备注是否包含特殊字符
      if (specialName) {
        wx.showModal({
          showCancel: false,
          content: '您的备注中包含特殊字符，请正确输入',
          success(res) {
            if (res.confirm) {

            }
          }
        })
        return false
      }
    wx.showModal({
      content: '提交订单？',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          let json = {
            token: app.globalData.token,
            refund_money: that.data.afterForm.refund_money || 0,
            id: that.data.afterForm.id,
            user_money: 0,
            refund_integral: that.data.afterForm.refund_integral || 0,
            status: that.data.afterForm.status,
            refund_mark: that.data.afterForm.refund_mark
          }

          myRequest.EasyHttp.post(api.reqUrls.afterHandle, json).then((res) => {
            console.log(888)
            console.log(999, res)
            if (res.data.status == 1) {
              wx.showToast({
                title: '处理成功',
                icon: 'success',
                duration: 2000
              })
              that.hintCancel()
              that.getData()
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'error',
                duration: 2000
              })
              that.hintCancel()
            }
          }).catch(err => {
            console.log(777, err)
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
   // 判断姓名中是否有表情
   hasSpecial(substring) {
    if (substring) {
      // 判断是否有表情
      var reg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig
      if (reg.test(substring)) {
        return true;
      }
      // 判断是否有特殊字符
      // var regs = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/;
      var regs = /^.*$/
      if (!regs.test(substring)) {
        return true;
      }
    }
  },
  showImg(e) {
    const that = this;
    let imglist = [];
    e.target.dataset.imglist.forEach(res => {
      imglist.push(that.data.domain + res)
    })
    let itemImg = e.target.dataset.itemimg;
    wx.previewImage({
      current: that.data.domain, // 当前显示图片的http链接
      urls: imglist // 需要预览的图片http链接列表
    })
  },
  // 获取表单输入内容
  changeInputContent(e) {
    const that = this;
    that.setData({
      keyword: e.detail.value
    })
  },
  //分类切换
  orderChange(e) {
    const that = this;
    that.setData({
      [`form.orderIndex`]: e.detail.value,
      page: 1,
      listData: [],
      isEnd: false,
      keyword: '',
      indexx: 0,
      shipping_mode: '10',
    })
    that.getnowdate()
    that.getData()
  },
  // 提交搜索
  searchSubmit() {
    const that = this;
    that.setData({
      scrollTop: 0,
      page: 1,
      listData: [],
      isEnd: false
    })
    that.getData()
  },
  //分类状态切换
  disposeChange(e) {
    const that = this;
    that.setData({
      [`form.disposeIndex`]: e.detail.value,
      page: 1,
      listData: [],
      isEnd: false,
      keyword: '',
      indexx: 0,
      shipping_mode: '10',
    })
    that.getnowdate()
    that.getData()
  },
  //去发货
  deliver(e) {
    const that = this;
    var valueList = [];
    wx.showModal({
      content: '是否发货',
      showCancel: true,
      confirmText: "确定",
      confirmColor: "#eb3223",
      success(res) {
        if (res.confirm) {
          let json = {
            token: app.globalData.token,
            order_id: e.currentTarget.dataset.order_id
          }
          myRequest.EasyHttp.post(api.reqUrls.deliveryHandle, json).then((res) => {
            if (res.data.status == 1) {
              wx.showToast({
                title: '发货成功',
                icon: 'success',
                duration: 2000
              })
              that.setData({
                page: 1
              })
              that.getData()
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'error',
                duration: 2000
              })
            }
          })
        }
      }
    })
  },
  //去发货多选
  doubledeliver() {
    const that = this;
    var valueList = [];
    that.data.listData.forEach(item => {
      if (item.checked) {
        valueList.push(item.order_id)
      }
    })
    console.log(JSON.stringify(valueList), 6666)
    wx.showModal({
      content: '是否发货',
      showCancel: true,
      confirmText: "确定",
      confirmColor: "#eb3223",
      success(res) {
        if (res.confirm) {
          let json = {
            token: app.globalData.token,
            ids: JSON.stringify(valueList)
          }
          myRequest.EasyHttp.post(api.reqUrls.send_batchHandle, json).then((res) => {
            if (res.data.status == 1) {
              wx.showToast({
                title: '发货成功',
                icon: 'success',
                duration: 2000
              })
              that.setData({
                page: 1
              })
              that.getData()
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'error',
                duration: 2000
              })
            }
          })
        }
      }
    })
  },
  //退款单去处理
  dispose(e) {
    const that = this;
    that.setData({
      hintSow: true,
      hintType: 1,
      [`afterForm.orderId`]: e.currentTarget.dataset.order_id
    })
  },
  //售后去处理
  afterSale(e) {
    const that = this;
    let json = {
      id: e.currentTarget.dataset.order_id,
      token: app.globalData.token,
    }
    myRequest.EasyHttp.post(api.reqUrls.afterInfo, json).then((res) => {
      if (res.data.status == 1) {
        that.setData({
          afterDec: res.data.result.goods,
          hintSow: true,
          hintType: 2,
          [`afterForm.id`]: e.currentTarget.dataset.order_id,
          [`afterForm.refund_integrals`]: res.data.result.order.integral,
          [`afterForm.refund_moneys`]: res.data.result.order.order_amount,
          [`afterForm.user_moneys`]: res.data.result.order.user_money
        })
      }

    })

  },
  //拨打电话
  phone(e) {
    console.log(e)
    let phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  getData() {
    const that = this;
    let json = {
      token: app.globalData.token,
      limit: that.data.limit,
      page: that.data.page,
      handle_status: that.data.form.disposeIndex,
      phone: that.data.keyword
    }
    if (that.data.form.orderIndex == 1 && that.data.form.disposeIndex == 0) {
      json.shipping_mode = that.data.shipping_mode,
        json.begin = that.data.start_date,
        json.end = that.data.end_date
    }
    switch (that.data.form.orderIndex) {
      case '1':
        myRequest.EasyHttp.post(api.reqUrls.orderList, json).then((res) => {

          wx.hideLoading();
          wx.stopPullDownRefresh();
          wx.hideNavigationBarLoading();
          if (res.data.status == 1) {
            var list = res.data.result.paginate.data
            list.forEach(item => {
              item.checked = false;
            })
            that.setData({
              listData: res.data.result.paginate.data
            })
          }
        })
        break;
      case '2':
        myRequest.EasyHttp.post(api.reqUrls.refundList, json).then((res) => {
          console.log(222)
          wx.hideLoading();
          wx.stopPullDownRefresh();
          wx.hideNavigationBarLoading();
          if (res.data.status == 1) {
            that.setData({
              listData: res.data.result.paginate.data
            })
          }
        })
        break;
      case '3':
        myRequest.EasyHttp.post(api.reqUrls.afterList, json).then((res) => {
          console.log(333)
          wx.hideLoading();
          wx.stopPullDownRefresh();
          wx.hideNavigationBarLoading();
          if (res.data.status == 1) {
            res.data.result.paginate.data.forEach(item => {
              item.imgList = item.imgs.split(',')
            })
            that.setData({
              listData: res.data.result.paginate.data
            })
          }
        })
        break;
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    that.getnowdate()
    that.getData()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const that = this;
    // that.setData({
    //   hintSow: false
    // })
    that.getnowdate()
    const token = app.globalData.token;

    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const that = this;
    that.setData({
      page: 1,
    })
    wx.showNavigationBarLoading()
    that.getData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const that = this;
    if (!that.data.isEnd) {
      wx.showLoading({
        title: '加载中...',
      })
    }
    let page = that.data.page;
    page++;
    let json = {
      token: app.globalData.token,
      limit: that.data.limit,
      page: page,
      handle_status: that.data.form.disposeIndex,
      phone: that.data.keyword
    }
    if (that.data.form.orderIndex == 1 && that.data.form.disposeIndex == 0) {
      json.shipping_mode = that.data.shipping_mode,
        json.begin = that.data.start_date,
        json.end = that.data.end_date
    }
    switch (that.data.form.orderIndex) {
      case '1':
        myRequest.EasyHttp.post(api.reqUrls.orderList, json).then((res) => {
          wx.hideLoading();
          wx.stopPullDownRefresh();
          wx.hideNavigationBarLoading();
          if (res.data.result.paginate.data.length == 0) {
            that.setData({
              isEnd: true
            })
          } else {
            const listData = that.data.listData;
            res.data.result.paginate.data.forEach(res => {
              listData.push(res)
            })
            that.setData({
              page,
              listData
            })
          }
        })
        break;
      case '2':
        myRequest.EasyHttp.post(api.reqUrls.refundList, json).then((res) => {
          wx.hideLoading();
          wx.stopPullDownRefresh();
          wx.hideNavigationBarLoading();
          if (res.data.result.paginate.data.length == 0) {
            that.setData({
              isEnd: true
            })
          } else {
            const listData = that.data.listData;
            res.data.result.paginate.data.forEach(res => {
              listData.push(res)
            })
            that.setData({
              page,
              listData
            })
          }
        })
        break;
      case '3':
        myRequest.EasyHttp.post(api.reqUrls.afterList, json).then((res) => {
          wx.hideLoading();
          wx.stopPullDownRefresh();
          wx.hideNavigationBarLoading();
          if (res.data.result.paginate.data.length == 0) {
            that.setData({
              isEnd: true
            })
          } else {
            const listData = that.data.listData;
            res.data.result.paginate.data.forEach(res => {

              listData.push(res)
            })
            that.setData({
              page,
              listData
            })
          }
        })
        break;
    }

  },
  //详情
  orderInfo(e) {
    const id = e.currentTarget.dataset.order_id;
    console.log(id, 99999)
    wx.navigateTo({
      url: `/pages/part/pages/orderInfo/orderInfo?id=${id}`
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})